package com.rest.common.Exception;

import com.rest.common.model.Message;
import com.rest.common.model.RestResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalExceptionHandler{

    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Message handleException(Exception exception){
        exception.printStackTrace();
        logger.error(exception.toString());
        return new RestResponse<String>(false,Message.FAIL,"","系统未知异常");
    }


    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(CommonServerException.class)
    @ResponseBody
    public Message handleCommonException(CommonServerException exception){
        exception.printStackTrace();
        logger.error(exception.toString());
        return new RestResponse<String>(false,Message.FAIL,"服务器内部异常");
    }

    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Message handleMethodArgumentNotValidException(MethodArgumentNotValidException exception){
        exception.printStackTrace();
        String messages  = exception.getBindingResult().getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.toList()).toString();
        return new RestResponse<String>(false,"参数校验失败",messages);
    }

}
